<template>
  <div class="examine-container">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧分类列表 -->
      <div style="border-right: 1px solid #e5e5e5">
        <!-- 搜索框 -->
        <div class="search-section">
          <el-input
            v-model="searchText"
            placeholder="请输入内容"
            class="search-input"
            clearable
            @input="onInput"
          >
          </el-input>
        </div>
        <div class="left-panel">
          <!-- 检查项目 -->
          <div class="category-section" style="border-right: 1px solid #e5e5e5">
            <div
              v-for="category in projectCategory"
              :key="category.projectCategory"
              class="category-header"
              :class="{ active: activeCategory === category.projectCategory }"
              @click="
                setActiveCategory(category.projectCategory, category.typeList)
              "
            >
              <span class="category-name">{{
                category.projectCategoryText
              }}</span>
              <span class="category-count">
                {{
                  selectedItems.filter(
                    (item) =>
                      item.projectCategory === category.projectCategory ||
                      item.projectCategory === category.projectCategory
                  ).length
                }}
              </span>
            </div>
          </div>
          <div class="category-section">
            <div
              v-for="projectType in projectTypeList"
              :key="projectType.itemCode"
              class="category-header"
              :class="{
                active: selectedProjectType === projectType.projectType,
              }"
              @click="
                setSelectedProjectType(
                  projectType.projectType,
                  projectType.feeList
                )
              "
            >
              <span class="category-name">{{
                projectType.projectTypeText
              }}</span>
              <span class="category-count" v-if="projectType.count">{{
                projectType.count
              }}</span>
            </div>
          </div>
        </div>
        <!-- 检验项目 -->
        <!-- <div class="category-section">
          <div class="category-header" @click="setActiveCategory('inspection')">
            <span class="category-name">检验项目</span>
          </div>
          <div class="subcategory-section">
            <div class="subcategory-item">
              <span class="subcategory-name">DR</span>
            </div>
          </div>
        </div> -->
      </div>

      <!-- 右侧详情表格 -->
      <div class="right-panel">
        <div
          class="search-section"
          style="height: 60px; justify-content: right; width: 100%"
        >
          <span style="cursor: pointer" @click="onClose">×</span>
        </div>
        <div class="detail-table" v-if="pairedTableData.length > 0">
          <!-- 表格行 -->
          <div
            v-for="(pair, pairIndex) in pairedTableData"
            :key="pairIndex"
            class="table-row"
          >
            <!-- 左侧项目 -->
            <div
              v-if="pair.left"
              class="left-content"
              :class="{ selected: pair.left.selected }"
              @click="toggleRowSelection(pair.left)"
            >
              <div class="item-name">{{ pair.left.projectName }}</div>
              <div class="item-price">
                ¥ {{ ((pair.left.price ?? 0) / 100).toFixed(2) }}
              </div>
            </div>
            <div v-else class="left-content placeholder"></div>

            <!-- 右侧项目 -->
            <div
              v-if="pair.right"
              class="right-content"
              :class="{ selected: pair.right.selected }"
              @click="toggleRowSelection(pair.right)"
            >
              <div class="item-name">{{ pair.right.projectName }}</div>
              <!-- <div class="item-price">¥ {{ pair.right.price }}</div> -->
              <div class="item-price">
                ¥ {{ ((pair.right.price ?? 0) / 100).toFixed(2) }}
              </div>
            </div>
            <div v-else class="right-content placeholder"></div>
          </div>
        </div>
        <div v-else class="detail-table">
          <el-empty
            description="暂无数据"
            :image="emptyImage"
            :image-size="100"
          />
        </div>
      </div>
    </div>

    <!-- 底部已选项目 -->
    <div class="footer-section">
      <div class="selected-items">
        <el-tag
          v-for="item in selectedItems"
          :key="item.projectId"
          class="selected-tag"
          closable
          @close="removeSelectedItem(item)"
        >
          {{ item.projectName || item.name }}
        </el-tag>
      </div>
      <el-button type="primary" class="confirm-btn" @click="onConfirm">
        确定 {{ selectedItems.length }}
      </el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import stores from '@/store';
import emptyImage from '@/assets/icon/internet_empty_illustration.svg';
import { getFeeStandardList } from '@/api/formwork';
import { getFeeStandardListv2 } from '@/api/basedata';
const userBase = stores.useBaseDataStore();
// 响应式数据
const searchText = ref('');
const activeCategory = ref<string>('1');
const selectedProjectType = ref<string>('');
const selectedSubcategory = ref('');
const selectedItems = ref<any[]>([]);
const EXAM_TYPE = ref<any[]>([]);
const LAB_TYPE = userBase.getDictsSelect('LAB_TYPE');
const EXT_TYPE = userBase.getDictsSelect('EXT_TYPE');
const projectCategory = ref<any[]>([]);
const projectTypeList = ref<any[]>([]);
const emits = defineEmits(['close', 'confirm']);
const examine = defineProps({
  activeType: {
    type: String,
    default: 'inspection', // 默认值为 'inspection'
  },
});
const { activeType } = toRefs(examine);
// 方法
const setActiveCategory = (category: string, typeList: any[]) => {
  activeCategory.value = category;
  selectedProjectType.value = ''; // 重置项目类型选择
  if (category === '1') {
    projectTypeList.value = typeList;
    selectedProjectType.value = projectTypeList.value[0].projectType;
    setSelectedProjectType(
      projectTypeList.value[0].projectType,
      projectTypeList.value[0].feeList
    );
  } else if (category === '2') {
    projectTypeList.value = typeList;
    selectedProjectType.value = projectTypeList.value[0].projectType;
    setSelectedProjectType(
      projectTypeList.value[0].projectType,
      projectTypeList.value[0].feeList
    );
  } else if (category === '3') {
    projectTypeList.value = typeList;
    selectedProjectType.value = projectTypeList.value[0].projectType;
    setSelectedProjectType(
      projectTypeList.value[0].projectType,
      projectTypeList.value[0].feeList
    );
  } else {
    projectTypeList.value = [];
  }
};

// 计算属性：将表格数据分成左右两列
type TableItem = {
  projectId: any;
  projectName?: string;
  price?: number;
  selected?: boolean;
  [key: string]: any;
};

const pairedTableData = computed(() => {
  const pairs: { left: TableItem | null; right: TableItem | null }[] = [];
  for (let i = 0; i < tableData.value.length; i += 2) {
    pairs.push({
      left: tableData.value[i]
        ? (tableData.value[i] as unknown as TableItem)
        : null,
      right: tableData.value[i + 1]
        ? (tableData.value[i + 1] as unknown as TableItem)
        : null,
    });
  }
  return pairs;
});
// 表格数据
const tableData = ref<TableItem[]>([]);

const onClose = () => {
  // 关闭逻辑
  emits('close');
  onreset();
  //console.log('关闭按钮被点击');
};
const setSelectedProjectType = async (projectType: string, feeList: any) => {
  selectedProjectType.value = projectType;
  // 这里可以根据选中的项目类型加载对应的数据
  //console.log('选中的项目类型:', projectType);
  tableData.value = feeList.map((item: { projectId: any }) => {
    const isSelected = selectedItems.value.some(
      (sel) => sel.projectId === item.projectId
    );
    return { ...item, selected: isSelected };
  });
  // const data = {
  //   projectCategory: activeCategory.value,
  //   projectType: projectType,
  //   projectName: searchText.value,
  // };
  // const feeStandardList = await getFeeStandardList(data);
  // if (feeStandardList.code !== '200') {
  //   //ElMessage.error(feeStandardList.msg);
  //   return;
  // }
  // if (feeStandardList && feeStandardList.data) {
  //   tableData.value = feeStandardList.data.map((item: { projectId: any }) => {
  //     const isSelected = selectedItems.value.some(
  //       (sel) => sel.projectId === item.projectId
  //     );
  //     return { ...item, selected: isSelected };
  //   }); // 初始化selected状态
  //   selectedItems;
  // } else {
  //   tableData.value = [];
  // }
  selectedSubcategory.value = ''; // 重置子分类选择
};

watch(
  () => examine.activeType,
  (newVal) => {
    getFeeStandardListv2(searchText.value).then((res) => {
      if (res.code === '200' && res.data) {
        if (newVal == '1') {
          setActiveCategory(newVal, res.data[0].typeList);
        } else if (newVal == '2') {
          setActiveCategory(newVal, res.data[1].typeList);
        }
        projectCategory.value = res.data;
        // EXAM_TYPE.value = res.data[0];
      } else {
        projectCategory.value = [];
        selectedItems.value = [];
        tableData.value = [];
        projectTypeList.value = [];
        activeCategory.value = '';
      }
    });
    activeCategory.value = newVal;
  },
  { deep: true, immediate: true }
);
onMounted(() => {
  // setActiveCategory('1');
});
const recharge = () => {
  getFeeStandardListv2(searchText.value).then((res) => {
    if (res.code === '200' && res.data) {
      setActiveCategory(activeCategory.value, res.data[0].typeList);
      projectCategory.value = res.data;
      activeCategory.value = res.data[0].projectCategory;
      // EXAM_TYPE.value = res.data[0];
    } else {
      selectedItems.value = [];
      tableData.value = [];
      projectTypeList.value = [];
      projectCategory.value = [];
      activeCategory.value = '';
    }
  });
};
const selectSubcategory = (subcategory: string) => {
  selectedSubcategory.value = subcategory;
};
// 确认选择，将选中项传递给父组件
const onConfirm = () => {
  // 触发自定义事件，传递选中项
  emits('confirm', selectedItems.value);
  // 关闭弹窗
  emits('close');
  activeType.value = '';
  onreset();
};
const toggleRowSelection = (item: any) => {
  //console.log(item);

  item.selected = !item.selected;
  if (item.selected) {
    selectedItems.value.push(item);
  } else {
    const index = selectedItems.value.findIndex(
      (selected) => selected.projectId === item.projectId
    );
    if (index > -1) {
      selectedItems.value.splice(index, 1);
    }
  }
};
const onreset = () => {
  // 触发自定义事件，传递选中项
  selectedItems.value = [];
  tableData.value = [];
  projectTypeList.value = [];
  activeCategory.value = '';
  searchText.value = '';
  // 重置 projectCategory.value 里的 selected 字段
  if (Array.isArray(projectCategory.value)) {
    projectCategory.value.forEach((cat) => {
      if (Array.isArray(cat.children)) {
        cat.children.forEach((child: any) => {
          if (Array.isArray(child.children)) {
            child.children.forEach((child: { selected: boolean }) => {
              child.selected = false;
            });
          }
        });
      }
    });
  }
  //console.log(projectCategory.value);
};
defineExpose({
  onreset,
});
const onInput = (e: any) => {
  recharge();
  // setSelectedProjectType(selectedProjectType.value)
};
const removeSelectedItem = (item: any) => {
  const tableItem = tableData.value.find(
    (data) => data.projectId === item.projectId
  );
  if (tableItem) {
    tableItem.selected = false;
  }
  const index = selectedItems.value.findIndex(
    (selected) => selected.projectId === item.projectId
  );
  if (index > -1) {
    selectedItems.value.splice(index, 1);
  }
};
</script>
<style lang="scss" scoped>
.examine-container {
  width: 100%;
  height: 500px;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;

  .search-section {
    background: white;
    display: flex;
    align-items: center;
    padding: 10px 15px;

    .search-input {
      flex: 1;
      max-width: 400px;

      :deep(.el-input__wrapper) {
        border-radius: 8px;
        height: 40px;
      }

      .search-icon {
        color: #999;
      }
    }

    .close-icon {
      font-size: 20px;
      color: #999;
      cursor: pointer;
      padding: 10px;
    }
  }

  .main-content {
    flex: 1;
    display: flex;

    .left-panel {
      width: 286px;
      border-right: 1px solid #e5e5e5;
      display: flex;

      .category-section {
        width: 100%;
        height: 400px;
        overflow: auto;

        .category-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          cursor: pointer;
          font-size: 14px;
          padding: 0px 15px;
          font-weight: 500;
          border-bottom: 1px solid #e5e5e5;
          height: 46px;

          &.active {
            background: rgba(22, 173, 164, 0.08);
            border-radius: 0px 0px 0px 0px;
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            font-size: 14px;
            color: #16ada4;
          }

          .category-count {
            font-size: 12px;
            text-align: center;
          }
        }

        .subcategory-section {
          .subcategory-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 30px;
            cursor: pointer;
            font-size: 13px;
            color: #666;
            background: white;
            border-bottom: 1px solid #f0f0f0;

            &.active {
              background: #e6f7ff;
              color: #00d4aa;
            }

            .subcategory-count {
              background: #f0f0f0;
              padding: 2px 6px;
              border-radius: 10px;
              font-size: 11px;
              min-width: 16px;
              text-align: center;
            }
          }
        }
      }
    }

    .right-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      background-color: white;

      .detail-table {
        overflow: auto;
        height: 420px;
        border-top: 1px solid #e5e5e5;

        .table-row {
          display: flex;
          padding: 0;
          border-bottom: 1px solid #f0f0f0;

          .left-content,
          .right-content {
            flex: 1;
            padding: 12px 20px;
            display: flex;
            justify-content: space-between;
            cursor: pointer;
            transition: all 0.2s;

            &.selected {
              background: #e6f7ff;
            }

            &.placeholder {
              cursor: default;
              opacity: 0;
            }

            .item-name {
              font-size: 14px;
              color: #333;
              font-weight: 500;
            }

            .item-price {
              font-size: 13px;
              color: #666;
            }
          }

          .right-content {
            border-left: 1px solid #f0f0f0;
          }
        }
      }
    }
  }

  .footer-section {
    padding: 20px;
    background: #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #e5e5e5;

    .selected-items {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      flex: 1;

      .selected-tag {
        --el-tag-bg-color: #e6f7ff;
        --el-tag-border-color: #b3d8ff;
        --el-tag-text-color: #00d4aa;
        background: rgba(22, 173, 164, 0.08);
        border: 1px solid #16ada4;
        font-size: 12px;
        padding: 6px 12px;
        border-radius: 20px;
      }
    }

    .confirm-btn {
      margin-left: 20px;
    }
  }
}

// Element Plus 样式覆盖
:deep(.el-button) {
  &.is-primary {
    background: #00d4aa;
    border-color: #00d4aa;
  }
}

:deep(.el-tag__close) {
  color: #909090;

  &:hover {
    color: #909090;
    color: white;
  }
}
</style>
